﻿using Common.Contract;
using Common.Contract.Authentication;
using Common.Contract.Authentication.Record;
using Common.Contract.Authentication.Request;
using Common.Contract.Authentication.Response;
using Common.Contract.Customer.Record;
using Common.Contract.Paging;
using Common.Contract.SystemConfig.Record;
using Common.Data;
using Common.Data.Repository.Enum;
using Common.Service;
using Common.Service.DataTables;
using Common.Type;
using Common.Util;
using Newtonsoft.Json.Linq;
using SMECustomerWebsite.Core.Configuration;
using SMECustomerWebsite.Filters;
using SMECustomerWebsite.Models.ViewModels.Account;
using SMECustomerWebsite.Models.ViewModels.DaoManager;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;

namespace SMECustomerWebsite.Controllers
{
    public class DaoManagerController : ControllerBase
    {
        #region Dao Registration
        public const string PrefixChangeDaoId = "CHD";
        public const string PrefixCreateDaoId = "CRD";
        [ChildActionOnly]
        [Authorize]
        public ActionResult ImportFormCreateDaoRequest()
        {

            return PartialView();
        }

        [ChildActionOnly]
        [Authorize]
        public ActionResult ImportResultCreateDaoRequest()
        {

            return PartialView();
        }
        public ActionResult DaoRegistrationRequestByGuest()
        {
            DaoInfoViewModel vm = new DaoInfoViewModel();
            List<BranchRecord> resultCustomer = GetListBranches();
            vm.ListBranch = new List<SelectListItem>();
            vm.ListBranch.Add(new SelectListItem
            {
                Text = "--- Chọn chi nhánh ---",
                Value = "",
                Selected = true
            });

            vm.ListBranch.AddRange(resultCustomer.Select(x => new SelectListItem
            {
                Text = x.BranchName,
                Value = x.BranchCodeSme
            }).ToList());

            return View(vm);
        }
        [Authorize]
        [CustomActionFilter]
        public ActionResult AddCreateDaoRequest(DaoInfoViewModel vm)
        {
            List<BranchRecord> resultCustomer = GetListBranches();
            vm.ListBranch = new List<SelectListItem>();
            vm.ListBranch.Add(new SelectListItem
            {
                Text = "--- Chọn chi nhánh ---",
                Value = "",
                Selected = true
            });

            vm.ListBranch.AddRange(resultCustomer.Select(x => new SelectListItem
            {
                Text = x.BranchName,
                Value = x.BranchCodeSme
            }).ToList());
            vm.CurrentUser = CurrentUserRecord;
            return View(vm);
        }

        [Authorize]
        [CustomActionFilter]
        public ActionResult ListRequestCreateDao(DaoInfoViewModel vm = null)
        {
            vm.CurrentUser = CurrentUserRecord;
            return View(vm);
        }

        [HttpPost]
        [AllowAnonymous]
        public ActionResult DaoRegistrationRequestByGuest(DaoInfoViewModel model, string ReturnUrl)
        {
            DaoInfoViewModel vm = new DaoInfoViewModel();
            bool isUpdate = false;
            string error = string.Empty;
            ModelState.Clear(); //clear old status
            List<BranchRecord> resultCustomer = GetListBranches();
            model.ListBranch = new List<SelectListItem>();
            model.ListBranch.Add(new SelectListItem
            {
                Text = "--- Chọn chi nhánh ---",
                Value = "",
                Selected = true
            });

            model.ListBranch.AddRange(resultCustomer.Select(x => new SelectListItem
            {
                Text = x.BranchName,
                Value = x.BranchCodeSme
            }).ToList());

            try
            {
                string fName = "";
                if (ModelState.IsValid)
                {
                    HttpPostedFileBase file = model.File;
                    //Save file content goes here
                    if (file != null && file.ContentLength > 0)
                    {
                        fName = file.FileName;
                        if (ALLOW_FILE_DAO_MANAGEMENT.Contains(Path.GetExtension(fName).ToLower()))
                        {

                            var originalDirectory = new DirectoryInfo(string.Format("{0}File/OfferLetter/{1}/{2}", Server.MapPath(@"\"), DateTime.Now.Year, DateTime.Now.Month));
                            string linkFileLocation = UploadFile(originalDirectory, file);

                            var linkFile = string.Format("/File/OfferLetter/{0}/{1}/{2}", DateTime.Now.Year, DateTime.Now.Month, file.FileName);
                            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
                            {
                                ResponseRecord response = null;

                                RequestCreateDaoRecord userRequest = new RequestCreateDaoRecord
                                {
                                    Pic = CurrentUserRecord == null ? model.Email.Split('@').FirstOrDefault() : CurrentUserRecord.UserName,
                                    FullName = model.FullName,
                                    BranchId = (CurrentUserRecord == null || string.IsNullOrEmpty(CurrentUserRecord.UserName)) ? model.Branch : CurrentUserRecord.BranchCode,
                                    Email = model.Email,
                                    PositionName = model.PositionName,
                                    Cif = model.Cif,
                                    StaffId = model.StaffId,
                                    PathOfferLetter = linkFile,
                                    LegalId = model.LegalId,
                                    Phone = model.Phone
                                };
                                UpdateCreateDaoRequestRequest request = new UpdateCreateDaoRequestRequest
                                {
                                    Header = new RequestHeaderRecord
                                    {
                                        ApplicationKey = SystemConfiguration.ApplicationKey,
                                        CallerName = "SMEsCustomer360Degree.Controllers.AdminChecklistController.UpdateRule"
                                    },
                                    Record = userRequest
                                };
                                response = serviceClient.Proxy.UpdateRequestDaoByGuest(request);
                                isUpdate = response.IsSuccess;
                                error = response.ErrorMessage;
                            }
                        }
                        else
                        {
                            isUpdate = false;
                            error = "File sai định dạng";
                        }
                    }
                    else
                    {
                        isUpdate = false;
                        error = "Yeu cau nhap thu moi";
                    }
                }
            }
            catch (Exception ex)
            {
                isUpdate = false;
                error = ex.ToString();
            }
            if (isUpdate)
            {
                if (CurrentUserRecord == null || string.IsNullOrEmpty(CurrentUserRecord.UserName))
                {
                    LoginViewModel successModel = new LoginViewModel();
                    successModel.MessageType = MessageType.Success;
                    successModel.Message = "Yêu cầu đã được khởi tạo/phê duyệt, vui lòng theo dõi email để biết kết quả từ hệ thống";
                    return RedirectToAction("Login", "Account", successModel);
                }
                else
                {
                    string cookieName = CurrentUserRecord.UserName + "CRDSuccess";
                    CreateCookie(cookieName, "Create request successfully");
                    return RedirectToAction("ListRequestCreateDao", "DaoManager", vm);
                }
            }
            else
            {
                string cookieName = CurrentUserRecord.UserName + "CRDError";
                CreateCookie(cookieName, error);
                if (CurrentUserRecord != null && !string.IsNullOrEmpty(CurrentUserRecord.UserName))
                {
                    return RedirectToAction("AddCreateDaoRequest", "DaoManager", model);
                }
                else
                {
                    return View(model);
                }
            }
        }
        [Authorize]
        [HttpPost]
        public ActionResult ListRequestCreateDaoData(DataTablesPageRequest pageRequest)
        {
            DataTableResponse pageResponse = null;
            var customerRecords = new RetrieveListRequestCreateDaoByUserResponse();
            List<object[]> listCust = new List<object[]>();
            FilterRecord filter = GetBaseFilter(pageRequest.SearchColumns);
            List<string> searchColumn = pageRequest.SearchColumns;
            switch (CurrentUserRecord.GroupIdentifier)
            {
                case "1":
                    filter.RequestId = searchColumn[2];
                    filter.StaffId = searchColumn[3];
                    filter.DaoName = searchColumn[4];
                    filter.ContractType = searchColumn[5];
                    filter.Email = searchColumn[6];
                    filter.RequestStatus = searchColumn[7];
                    filter.CusOpenDate = searchColumn[8];
                    break;
                case "2":
                    filter.RequestId = searchColumn[1];
                    filter.StaffId = searchColumn[2];
                    filter.DaoName = searchColumn[3];
                    filter.ContractType = searchColumn[4];
                    filter.Email = searchColumn[5];
                    filter.RequestStatus = searchColumn[6];
                    filter.CusOpenDate = searchColumn[7];
                    break;
                case "3":
                    filter.RequestId = searchColumn[0];
                    filter.StaffId = searchColumn[1];
                    filter.DaoName = searchColumn[2];
                    filter.ContractType = searchColumn[3];
                    filter.Email = searchColumn[4];
                    filter.RequestStatus = searchColumn[5];
                    filter.CusOpenDate = searchColumn[6];
                    break;
                case "6":
                    filter.RequestId = searchColumn[0];
                    filter.StaffId = searchColumn[1];
                    filter.DaoName = searchColumn[2];
                    filter.ContractType = searchColumn[3];
                    filter.Email = searchColumn[4];
                    filter.RequestStatus = searchColumn[5];
                    filter.CusOpenDate = searchColumn[6];
                    break;
                default:
                    break;
            }
            customerRecords = RetrieveListCreateDaoRequest(filter, pageRequest);
            var resultCustomer = (customerRecords == null || customerRecords.Records == null) ? new List<RequestCreateDaoRecord>() : customerRecords.Records;

            switch (CurrentUserRecord.GroupIdentifier)
            {
                case "1":
                    listCust = resultCustomer.Select(x => new object[]{
                                                                 x.Zone,
                                                                 x.Branch,
                                                                 string.Format("{0}{1}",PrefixCreateDaoId, x.RequestId),
                                                                 x.StaffId,
                                                                 x.FullName,
                                                                 x.PositionName,
                                                                 x.Email,
                                                                 x.RejectPerson + EnumHelper<StatusRequestCreateDaoEnum>.GetDisplayValue((StatusRequestCreateDaoEnum)x.StatusCreateDaoRequest),
                                                                 x.CreateRequestTime.ToString(),
                                                                 x.PathOfferLetter,
                                                                 x.RequestId,
                                                                 x.NeedApproved,
                                                                 x.NeedUploadOfferLetter,
                                                                 x.CanReject
                        }).ToList();
                    break;
                case "2":
                    listCust = resultCustomer.Select(x => new object[]{
                                                                 x.Branch,
                                                                 string.Format("{0}{1}",PrefixCreateDaoId, x.RequestId),
                                                                 x.StaffId,
                                                                 x.FullName,
                                                                 x.PositionName,
                                                                 x.Email,
                                                                 x.RejectPerson + EnumHelper<StatusRequestCreateDaoEnum>.GetDisplayValue((StatusRequestCreateDaoEnum)x.StatusCreateDaoRequest),
                                                                 x.CreateRequestTime.ToString(),
                                                                 x.PathOfferLetter,
                                                                 x.RequestId,
                                                                 x.NeedApproved,
                                                                 x.NeedUploadOfferLetter,
                                                                 x.CanReject
                        }).ToList();
                    break;
                case "3":
                    if (CurrentUserRecord.Position.Equals("Hub Manager"))
                    {
                        listCust = resultCustomer.Select(x => new object[]{
                                                                 string.Format("{0}{1}",PrefixCreateDaoId, x.RequestId),
                                                                 x.StaffId,
                                                                 x.FullName,
                                                                 x.PositionName,
                                                                 x.Email,
                                                                 x.RejectPerson + EnumHelper<StatusRequestCreateDaoEnum>.GetDisplayValue((StatusRequestCreateDaoEnum)x.StatusCreateDaoRequest),
                                                                 x.CreateRequestTime.ToString(),
                                                                 x.PathOfferLetter,
                                                                 x.RequestId,
                                                                 x.NeedApproved,
                                                                 x.NeedUploadOfferLetter,
                                                                 x.CanReject
                        }).ToList();
                    }
                    else
                    {
                        listCust = resultCustomer.Select(x => new object[]{
                                                                 string.Format("{0}{1}",PrefixCreateDaoId, x.RequestId),
                                                                 x.StaffId,
                                                                 x.FullName,
                                                                 x.PositionName,
                                                                 x.Email,
                                                                 x.RejectPerson + EnumHelper<StatusRequestCreateDaoEnum>.GetDisplayValue((StatusRequestCreateDaoEnum)x.StatusCreateDaoRequest),
                                                                 x.CreateRequestTime.ToString(),
                                                                 x.PathOfferLetter,
                                                                 x.RequestId,
                                                                 x.NeedApproved,
                                                                 x.NeedUploadOfferLetter,
                                                                 x.CanReject
                        }).ToList();
                    }
                    break;
                case "4":
                    listCust = resultCustomer.Select(x => new object[]{
                                                                 string.Format("{0}{1}",PrefixCreateDaoId, x.RequestId),
                                                                 x.StaffId,
                                                                 x.FullName,
                                                                 x.PositionName,
                                                                 x.Email,
                                                                 x.RejectPerson + EnumHelper<StatusRequestCreateDaoEnum>.GetDisplayValue((StatusRequestCreateDaoEnum)x.StatusCreateDaoRequest),
                                                                 x.CreateRequestTime.ToString(),
                                                                 x.PathOfferLetter,
                                                                 x.RequestId,
                                                                 x.NeedApproved,
                                                                 x.NeedUploadOfferLetter,
                                                                 x.CanReject
                        }).ToList();
                    break;
                case "6":
                    listCust = resultCustomer.Select(x => new object[]{
                                                                 string.Format("{0}{1}",PrefixCreateDaoId, x.RequestId),
                                                                 x.StaffId,
                                                                 x.FullName,
                                                                 x.PositionName,
                                                                 x.Email,
                                                                 x.RejectPerson + EnumHelper<StatusRequestCreateDaoEnum>.GetDisplayValue((StatusRequestCreateDaoEnum)x.StatusCreateDaoRequest),
                                                                 x.CreateRequestTime.ToString(),
                                                                 x.PathOfferLetter,
                                                                 x.RequestId,
                                                                 x.NeedApproved,
                                                                 x.NeedUploadOfferLetter,
                                                                 x.CanReject
                        }).ToList();
                    break;
                default:
                    break;
            }
            pageResponse = new DataTableResponse
            {
                sEcho = pageRequest.Echo,
                iTotalRecords = customerRecords.Page.TotalRecords,
                sColumns = pageRequest.ColumnNames,
                aaData = listCust
            };
            return Json(pageResponse);
        }

        [Authorize]
        [CustomActionFilter]
        public ActionResult DownloadForm(string file)
        {
            var originalDirectory = new DirectoryInfo(string.Format("{0}File/OfferLetter", Server.MapPath(@"\")));

            string pathString = Path.Combine(originalDirectory.ToString());

            bool isExists = Directory.Exists(pathString);
            if (isExists)
            {
                return File(new FileStream(pathString + "/" + file, FileMode.Open), "content-dispostion", file);
            }

            throw new ArgumentException("Invalid file name of file not exist");
        }

        #endregion

        #region Change Dao
        [Authorize]
        [CustomActionFilter]
        public ActionResult ListChangeDaoRequest(ChangeDaoViewModel vm)
        {
            vm.CurrentUser = CurrentUserRecord;
            return View(vm);
        }

        [Authorize]
        [CustomActionFilter]
        public ActionResult AddChangeDaoRequest()
        {
            ChangeDaoViewModel vm = new ChangeDaoViewModel
            {
                CurrentUser = CurrentUserRecord
            };
            return View(vm);
        }


        [Authorize]
        [HttpPost]
        public ActionResult ListChangeDaoRequestData(DataTablesPageRequest pageRequest)
        {
            DataTableResponse pageResponse = null;
            var customerRecords = new RetrieveListChangeDaoRequestResponse();
            List<object[]> listCust = new List<object[]>();
            FilterRecord filter = GetBaseFilter(pageRequest.SearchColumns);
            switch (CurrentUserRecord.GroupIdentifier)
            {
                case "1":
                    filter.RequestId = pageRequest.SearchColumns[2];
                    filter.DaoName = pageRequest.SearchColumns[3];
                    filter.RequestStatus = pageRequest.SearchColumns[4];
                    filter.Description = pageRequest.SearchColumns[5];
                    filter.CusOpenDate = pageRequest.SearchColumns[6];
                    break;
                case "2":
                    filter.RequestId = pageRequest.SearchColumns[1];
                    filter.DaoName = pageRequest.SearchColumns[2];
                    filter.RequestStatus = pageRequest.SearchColumns[3];
                    filter.Description = pageRequest.SearchColumns[4];
                    filter.CusOpenDate = pageRequest.SearchColumns[5];
                    break;
                case "3":
                    filter.RequestId = pageRequest.SearchColumns[0];
                    filter.DaoName = pageRequest.SearchColumns[1];
                    filter.RequestStatus = pageRequest.SearchColumns[2];
                    filter.Description = pageRequest.SearchColumns[3];
                    filter.CusOpenDate = pageRequest.SearchColumns[4];
                    break;
                case "4":
                    filter.RequestId = pageRequest.SearchColumns[0];
                    filter.DaoName = pageRequest.SearchColumns[1];
                    filter.RequestStatus = pageRequest.SearchColumns[2];
                    filter.Description = pageRequest.SearchColumns[3];
                    filter.CusOpenDate = pageRequest.SearchColumns[4];
                    break;
                case "6":
                    filter.RequestId = pageRequest.SearchColumns[0];
                    filter.DaoName = pageRequest.SearchColumns[1];
                    filter.RequestStatus = pageRequest.SearchColumns[2];
                    filter.Description = pageRequest.SearchColumns[3];
                    filter.CusOpenDate = pageRequest.SearchColumns[4];
                    break;
                default:
                    break;
            }
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {

                RetrieveListChangeDaoRequestRequest request = new RetrieveListChangeDaoRequestRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.DaoManagerController.RetrieveListCreateDaoRequest"
                    },
                    Page = new PageRecord
                    {
                        PageSize = pageRequest == null ? 0 : pageRequest.DisplayLength,
                        PageIndex = pageRequest == null ? 0 : pageRequest.DisplayLength > 0 ? pageRequest.DisplayStart / pageRequest.DisplayLength : 0
                    },
                    Sort = new SortRecord
                    {
                        SortDir = pageRequest.SortDir,
                    },
                    CurrentUser = CurrentUserRecord,
                    Filter = filter
                };
                customerRecords = serviceClient.Proxy.RetrieveListChangeDaoRequest(request);
            }
            var resultCustomer = (customerRecords == null || customerRecords.Records == null) ? new List<ChangeDaoRequestRecord>() : customerRecords.Records;
            if (resultCustomer.Count > 0)
            {
                switch (CurrentUserRecord.GroupIdentifier)
                {
                    case "1":
                        listCust = resultCustomer.Select(x => new object[]{
                                                        x.Zone,
                                                        x.Branch,
                                                        string.Format("{0}{1}",PrefixChangeDaoId, x.Id),
                                                        x.Pic,
                                                        x.RejectPerson + EnumHelper<StatusChangeDaoEnum>.GetDisplayValue((StatusChangeDaoEnum)x.Status),
                                                        EnumHelper<ReasonChangeDaoEnum>.GetDisplayValue((ReasonChangeDaoEnum)x.Reason) + x.ReasonDescription,
                                                        x.CreatedDate.ToString(),
                                                        x.Id,
                                                        x.NeedApprove,
                                                        x.CanReject,
                                                        x.IsDeviation

                        }).ToList();
                        break;
                    case "2":
                        listCust = resultCustomer.Select(x => new object[]{
                                                        x.Branch,
                                                        string.Format("{0}{1}",PrefixChangeDaoId, x.Id),
                                                        x.Pic,
                                                        x.RejectPerson + EnumHelper<StatusChangeDaoEnum>.GetDisplayValue((StatusChangeDaoEnum)x.Status),
                                                        EnumHelper<ReasonChangeDaoEnum>.GetDisplayValue((ReasonChangeDaoEnum)x.Reason) + x.ReasonDescription,
                                                        x.CreatedDate.ToString(),
                                                        x.Id,
                                                        x.NeedApprove,
                                                        x.CanReject,
                                                        x.IsDeviation
                        }).ToList();
                        break;
                    case "3":
                        if (CurrentUserRecord.Position.Equals("Hub Manager"))
                        {
                            listCust = resultCustomer.Select(x => new object[]{
                                                        string.Format("{0}{1}",PrefixChangeDaoId, x.Id),
                                                        x.Pic,
                                                        x.RejectPerson + EnumHelper<StatusChangeDaoEnum>.GetDisplayValue((StatusChangeDaoEnum)x.Status),
                                                        EnumHelper<ReasonChangeDaoEnum>.GetDisplayValue((ReasonChangeDaoEnum)x.Reason)+ x.ReasonDescription,
                                                        x.CreatedDate.ToString(),
                                                        x.Id,
                                                        x.NeedApprove,
                                                        x.CanReject,
                                                        x.IsDeviation

                        }).ToList();
                        }
                        else
                        {
                            listCust = resultCustomer.Select(x => new object[]{
                                                        string.Format("{0}{1}",PrefixChangeDaoId, x.Id),
                                                        x.Pic,
                                                        x.RejectPerson + EnumHelper<StatusChangeDaoEnum>.GetDisplayValue((StatusChangeDaoEnum)x.Status),
                                                        EnumHelper<ReasonChangeDaoEnum>.GetDisplayValue((ReasonChangeDaoEnum)x.Reason)+ x.ReasonDescription,
                                                        x.CreatedDate.ToString(),
                                                        x.Id,
                                                        x.NeedApprove,
                                                        x.CanReject,
                                                        x.IsDeviation
                        }).ToList();
                        }
                        break;
                    case "4":
                        listCust = resultCustomer.Select(x => new object[]{
                                                        string.Format("{0}{1}",PrefixChangeDaoId, x.Id),
                                                        x.Pic,
                                                        x.RejectPerson + EnumHelper<StatusChangeDaoEnum>.GetDisplayValue((StatusChangeDaoEnum)x.Status),
                                                        EnumHelper<ReasonChangeDaoEnum>.GetDisplayValue((ReasonChangeDaoEnum)x.Reason)+ x.ReasonDescription,
                                                        x.CreatedDate.ToString(),
                                                        x.Id,
                                                        x.NeedApprove,
                                                        x.CanReject,
                                                        x.IsDeviation

                        }).ToList();
                        break;
                    case "6":
                        listCust = resultCustomer.Select(x => new object[]{
                                                        string.Format("{0}{1}",PrefixChangeDaoId, x.Id),
                                                        x.Pic,
                                                        x.RejectPerson + EnumHelper<StatusChangeDaoEnum>.GetDisplayValue((StatusChangeDaoEnum)x.Status),
                                                        EnumHelper<ReasonChangeDaoEnum>.GetDisplayValue((ReasonChangeDaoEnum)x.Reason)+ x.ReasonDescription,
                                                        x.CreatedDate.ToString(),
                                                        x.Id,
                                                        x.NeedApprove,
                                                        x.CanReject,
                                                        x.IsDeviation
                        }).ToList();
                        break;
                    default:
                        break;
                }
            }
            pageResponse = new DataTableResponse
            {
                sEcho = pageRequest.Echo,
                iTotalRecords = customerRecords.Page.TotalRecords,
                sColumns = pageRequest.ColumnNames,
                aaData = listCust
            };
            return Json(pageResponse);
        }


        [Authorize]
        [HttpPost]
        public ActionResult ChangeDaoCifRequestDetail(DataTablesPageRequest pageRequest, string requestId)
        {

            List<ChangeDaoCifRecord> resultCustomer = new List<ChangeDaoCifRecord>();
            DataTableResponse pageResponse = new DataTableResponse()
            {
                sEcho = pageRequest.Echo,
                iTotalRecords = 0,
                sColumns = pageRequest.ColumnNames,
                aaData = new List<object[]>()
            };
            int RequestId;
            if (int.TryParse(requestId, out RequestId))
            {
                using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
                {
                    RetrieveChangeDaoCifRequest request = new RetrieveChangeDaoCifRequest
                    {
                        Header = new RequestHeaderRecord
                        {
                            ApplicationKey = SystemConfiguration.ApplicationKey,
                            CallerName = "SMEsCustomer360Degree.Controllers.CustomerManagerController.CustFeedbackDetail"
                        },
                        Page = new PageRecord
                        {
                            PageSize = pageRequest.DisplayLength,
                            PageIndex = pageRequest.DisplayLength > 0 ? pageRequest.DisplayStart / pageRequest.DisplayLength : 0
                        },
                        CurrentUser = CurrentUserRecord,
                        ChangeDaoRequestId = RequestId
                    };
                    var customerRecords = new RetrieveChangeDaoCifResponse();
                    customerRecords = serviceClient.Proxy.RetrieveChangeDaoCif(request);
                    resultCustomer = (customerRecords == null || customerRecords.Records == null) ? new List<ChangeDaoCifRecord>() : customerRecords.Records;
                    pageResponse = new DataTableResponse
                    {
                        sEcho = pageRequest.Echo,
                        iTotalRecords = customerRecords.Page.TotalRecords,
                        sColumns = pageRequest.ColumnNames,
                        aaData = resultCustomer.Select(x => new object[]{
                                                             x.Id,
                                                             x.Cif,
                                                             x.CustomerName,
                                                             x.Segment,
                                                             x.NewDao,
                                                             x.LastUpdateData.HasValue?x.LastUpdateData.Value.ToString() :  string.Empty,
                                                             x.ListChangeDaoProduct,
                                                             x.IsApproved,
                                                             x.IsDisabled,
                                                             x.Status,
                                                             x.CheckCondition
                    }).ToList()
                    };
                }
            }
            return Json(pageResponse);
        }

        [Authorize]
        [HttpPost]
        public ActionResult GetChangeDaoInfo(DataTablesPageRequest pageRequest, string data)
        {
            List<ChangeDaoCifRecord> resultCustomer = new List<ChangeDaoCifRecord>();
            DataTableResponse pageResponse = new DataTableResponse()
            {
                sEcho = pageRequest.Echo,
                iTotalRecords = 0,
                sColumns = pageRequest.ColumnNames,
                aaData = new List<object[]>()
            };
            if (data.Equals("[]"))
            {
                return Json(pageResponse);
            }
            List<ChangeDaoCifRecord> listChangeDaoCif = new List<ChangeDaoCifRecord>();
            JArray arrayCif = new JArray();
            if (!string.IsNullOrEmpty(data))
            {
                arrayCif = JArray.Parse(data);
            }

            for (int i = 0; i < arrayCif.Count; i++)
            {
                var changeDaoCifItem = arrayCif[i][0];
                var cif = changeDaoCifItem[0].ToString();
                var newDao = changeDaoCifItem[1].ToString();
                ChangeDaoCifRecord changeDaoCifRecord = new ChangeDaoCifRecord
                {
                    Cif = cif,
                    NewDao = newDao,
                    IsApproved = changeDaoCifItem[2].ToString().ToLower().Equals("true")
                };
                if (arrayCif[i].Count() > 1)
                {
                    var changeDaoProductItem = arrayCif[i][1];
                    if (changeDaoProductItem.Count() > 0)
                    {
                        List<ChangeDaoProductCheckedRecord> listProductRecord = new List<ChangeDaoProductCheckedRecord>();
                        for (int j = 0; j < changeDaoProductItem.Count(); j++)
                        {
                            ChangeDaoProductCheckedRecord productRecord = new ChangeDaoProductCheckedRecord
                            {
                                NoProduct = changeDaoProductItem[j][2].ToString(),
                                IsApproved = changeDaoProductItem[j][1].ToString().ToLower().Equals("true")
                            };
                            listProductRecord.Add(productRecord);
                        }
                        changeDaoCifRecord.ListChangeDaoProduct = listProductRecord;
                    }
                }
                listChangeDaoCif.Add(changeDaoCifRecord);
            }

            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {
                RetrieveChangeDaoCifRequest request = new RetrieveChangeDaoCifRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.CustomerManagerController.CustFeedbackDetail"
                    },
                    Page = new PageRecord
                    {
                        PageSize = pageRequest.DisplayLength,
                        PageIndex = pageRequest.DisplayLength > 0 ? pageRequest.DisplayStart / pageRequest.DisplayLength : 0
                    },
                    CurrentUser = CurrentUserRecord,
                    ListCif = listChangeDaoCif
                };
                var customerRecords = new RetrieveChangeDaoCifResponse();
                customerRecords = serviceClient.Proxy.RetrieveChangeDaoCifByListCif(request);
                resultCustomer = (customerRecords == null || customerRecords.Records == null) ? new List<ChangeDaoCifRecord>() : customerRecords.Records;
                pageResponse = new DataTableResponse
                {
                    sEcho = pageRequest.Echo,
                    iTotalRecords = customerRecords.Page.TotalRecords,
                    sColumns = pageRequest.ColumnNames,
                    aaData = resultCustomer.Select(x => new object[]{
                                                             x.NewDaoName,
                                                             x.Cif,
                                                             x.CustomerName,
                                                             x.Segment,
                                                             x.NewDao,
                                                             x.LastUpdateData.HasValue?x.LastUpdateData.Value.ToString() :  string.Empty,
                                                             x.ListChangeDaoProduct,
                                                             x.IsApproved,
                                                             x.IsDisabled,
                                                             x.CheckCondition
                    }).ToList()
                };
            }
            return Json(pageResponse);
        }
        #endregion

        #region Change Dao Ajax Methods
        [Authorize]
        [HttpPost]
        public ActionResult UpdateChangeDaoCifMultiple(string dataProduct, string reason, string reasonDescription, string check)
        {
            ModelState.Clear(); //clear old status
            bool isUpdate = false;

            List<ChangeDaoCifRecord> listChangeDaoCif = new List<ChangeDaoCifRecord>();
            JArray arrayCif = new JArray();
            if (!string.IsNullOrEmpty(dataProduct))
            {
                arrayCif = JArray.Parse(dataProduct);
            }

            for (int i = 0; i < arrayCif.Count; i++)
            {
                var changeDaoCifItem = arrayCif[i][0];
                var cif = changeDaoCifItem[0].ToString();
                var newDao = changeDaoCifItem[1].ToString();
                ChangeDaoCifRecord changeDaoCifRecord = new ChangeDaoCifRecord
                {
                    Cif = cif,
                    NewDao = newDao,
                    IsApproved = changeDaoCifItem[2].ToString().ToLower().Equals("true")
                };
                if (arrayCif[i].Count() > 1)
                {
                    var changeDaoProductItem = arrayCif[i][1];
                    if (changeDaoProductItem.Count() > 0)
                    {
                        List<ChangeDaoProductCheckedRecord> listProductRecord = new List<ChangeDaoProductCheckedRecord>();
                        for (int j = 0; j < changeDaoProductItem.Count(); j++)
                        {
                            ChangeDaoProductCheckedRecord productRecord = new ChangeDaoProductCheckedRecord
                            {
                                NoProduct = changeDaoProductItem[j][2].ToString(),
                                IsApproved = changeDaoProductItem[j][1].ToString().ToLower().Equals("true")
                            };
                            listProductRecord.Add(productRecord);
                        }
                        changeDaoCifRecord.ListChangeDaoProduct = listProductRecord;
                    }
                }
                listChangeDaoCif.Add(changeDaoCifRecord);
            }
            ResponseRecord response = null;
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {
                UpdateChangeDaoRequestRequest request = new UpdateChangeDaoRequestRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.PortfolioManagementController.EditAccountPlanningFinanceAction"
                    },
                    ListChangeDaoCif = listChangeDaoCif,
                    CurrentUser = CurrentUserRecord,
                    Record = new ChangeDaoRequestRecord
                    {
                        IsDeviation = check.ToLower().Equals("true"),
                        Reason = int.Parse(reason),
                        ReasonDescription = reasonDescription
                    }
                };
                response = serviceClient.Proxy.UpdateChangeDaoRequestMultiple(request);
                isUpdate = response.IsSuccess;
            }
            ChangeDaoViewModel vm = new ChangeDaoViewModel();
            if (isUpdate)
            {
                vm.MessageType = MessageType.Success;
                vm.Message = "Update Request successfully";
            }
            else
            {
                vm.MessageType = MessageType.Error;
                vm.Message = response.ErrorMessage;
            }

            return Json(vm);
        }


        [Authorize]
        [HttpPost]
        public ActionResult UpdateChangeDaoCif(string dataCif, string dataProduct, int requestId, string check)
        {
            ModelState.Clear(); //clear old status
            bool isUpdate = false;

            List<ChangeDaoCifRecord> listChangeDaoCif = new List<ChangeDaoCifRecord>();
            JArray arrayCif = new JArray();
            if (!string.IsNullOrEmpty(dataCif))
            {
                arrayCif = JArray.Parse(dataCif);
            }

            for (int i = 0; i < arrayCif.Count; i++)
            {
                var changeDaoCifItem = JArray.Parse(arrayCif[i].ToString().Trim('{', '}'));
                var nameCifID = changeDaoCifItem[0].ToString();
                var changeCifId = int.Parse(Regex.Replace(nameCifID, "[^0-9]+", string.Empty));
                ChangeDaoCifRecord changeDaoCifRecord = new ChangeDaoCifRecord
                {
                    Id = changeCifId,
                    IsApproved = changeDaoCifItem[1].ToString().ToLower().Equals("true")
                };
                listChangeDaoCif.Add(changeDaoCifRecord);
            }

            List<ChangeDaoProductCheckedRecord> listProduct = new List<ChangeDaoProductCheckedRecord>();

            JArray arrayProduct = new JArray();
            if (!string.IsNullOrEmpty(dataProduct))
            {
                arrayProduct = JArray.Parse(dataProduct);
            }
            for (int i = 0; i < arrayProduct.Count; i++)
            {
                var changeDaoProductItem = JArray.Parse(arrayProduct[i].ToString().Trim('{', '}'));
                var nameProductID = changeDaoProductItem[0].ToString();
                var changeProductId = int.Parse(Regex.Replace(nameProductID, "[^0-9]+", string.Empty));
                ChangeDaoProductCheckedRecord changeDaoProductRecord = new ChangeDaoProductCheckedRecord
                {
                    Id = changeProductId,
                    NeedApprove = changeDaoProductItem[1].ToString().ToLower().Equals("true")
                };
                listProduct.Add(changeDaoProductRecord);
            }
            ResponseRecord response = null;
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {
                UpdateChangeDaoRequestRequest request = new UpdateChangeDaoRequestRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.PortfolioManagementController.EditAccountPlanningFinanceAction"
                    },
                    ListChangeDaoCif = listChangeDaoCif,
                    CurrentUser = CurrentUserRecord,
                    ListChangeDaoProduct = listProduct,
                    Record = new ChangeDaoRequestRecord
                    {
                        Id = requestId,
                        IsDeviation = check.ToLower().Equals("true")
                    }
                };
                response = serviceClient.Proxy.UpdateChangeDaoRequestByCifAndProduct(request);
                isUpdate = response.IsSuccess;
            }
            ChangeDaoViewModel vm = new ChangeDaoViewModel();
            if (isUpdate)
            {
                vm.MessageType = MessageType.Success;
                vm.Message = "Update Request successfully";
            }
            else
            {
                vm.MessageType = MessageType.Error;
                vm.Message = response.ErrorMessage;
            }

            return Json(vm);
        }

        [Authorize]
        [HttpPost]
        public ActionResult RejectReasonChangeDaoRequest(ChangeDaoViewModel vm)
        {
            ResponseRecord response = new ResponseRecord();
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {
                ChangeDaoRequestRecord userRequest = new ChangeDaoRequestRecord
                {
                    Id = vm.Id,
                    Status = (int)StatusChangeDaoEnum.Reject,
                    RejectReason = vm.RejectReason
                };
                UpdateChangeDaoRequestRequest requestUpdate = new UpdateChangeDaoRequestRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.DaoManager.ApproveRequestCreateDao"
                    },
                    Record = userRequest,
                    CurrentUser = CurrentUserRecord
                };
                response = serviceClient.Proxy.UpdateRejectChangeDaoReason(requestUpdate);
                bool isUpdate = response.IsSuccess;

                if (!isUpdate)
                {
                    string cookieName = CurrentUserRecord.UserName + "CHDError";
                    CreateCookie(cookieName, response.ErrorMessage);
                }
                else
                {
                    string cookieName = CurrentUserRecord.UserName + "CHDSuccess";
                    CreateCookie(cookieName, "Reject request successfully");
                }
            }
            return RedirectToAction("ListChangeDaoRequest", "DaoManager");
        }
        [Authorize]
        [CustomActionFilter]
        [HttpPost]
        public ActionResult RejectChangeDaoRequest(int request)
        {
            ChangeDaoRequestRecord userRequest = new ChangeDaoRequestRecord
            {
                Id = request,
                Status = (int)StatusChangeDaoEnum.Reject
            };
            var result = UpdateChangeDaoStatus(userRequest);
            return Json(result);
        }

        [Authorize]
        [HttpPost]
        [CustomActionFilter]
        public ActionResult ImportResultChangeDaoRequest(FormCollection formCollection)
        {
            DaoInfoViewModel vm = new DaoInfoViewModel();
            try
            {

                if (Request != null)
                {
                    HttpPostedFileBase file = Request.Files["UploadedFile"];

                    if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
                    {
                        string now = DateTime.Now.ConvertToTimestamp().ToString();
                        string fileExtension = System.IO.Path.GetExtension(file.FileName);
                        string fileName = string.Format("BIC_RCDAO_{0}_{1}{2}", CurrentUserRecord.UserName, now, fileExtension);
                        if (fileExtension == ".xls" || fileExtension == ".xlsx")
                        {
                            var originalDirectory = new DirectoryInfo(Server.MapPath("~/File/OfferLetter/"));
                            string fileLocation = UploadFile(originalDirectory, file, fileName);

                            DataTable dt = ConvertXSLXtoDataTable(fileLocation, fileExtension);
                            List<ChangeDaoRequestRecord> listRequest = new List<ChangeDaoRequestRecord>();
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                var item = dt.Rows[i];
                                ChangeDaoRequestRecord record = new ChangeDaoRequestRecord
                                {
                                    Id = int.Parse(item[0].ToString()),
                                    Status = (int)StatusChangeDaoEnum.Done
                                };
                                listRequest.Add(record);
                            }

                            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
                            {
                                ResponseRecord response = null;

                                UpdateChangeDaoRequestRequest request = new UpdateChangeDaoRequestRequest
                                {
                                    Header = new RequestHeaderRecord
                                    {
                                        ApplicationKey = SystemConfiguration.ApplicationKey,
                                        CallerName = "SMEsCustomer360Degree.Controllers.AdminChecklistController.UpdateRule"
                                    },
                                    ListChangeDaoRequest = listRequest,
                                    CurrentUser = CurrentUserRecord
                                };
                                response = serviceClient.Proxy.UpdateStatusListChangeDaoRequest(request);
                                bool isUpdate = response.IsSuccess;
                                string error = response.ErrorMessage;
                                if (isUpdate)
                                {
                                    vm.MessageType = MessageType.Success;
                                    vm.Message = "Upload Result successfully";
                                }
                                else
                                {
                                    System.IO.File.Delete(fileLocation);
                                    vm.MessageType = MessageType.Error;
                                    vm.Message = response.ErrorMessage;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                vm.MessageType = MessageType.Error;
                vm.Message = ex.Message;
                throw;
            }
            return RedirectToAction("ListChangeDaoRequest", "DaoManager", vm);
        }

        [Authorize]
        [CustomActionFilter]
        [HttpPost]
        public ActionResult UploadFormChangeDaoRequest(ChangeDaoViewModel model)
        {
            ModelState.Clear(); //clear old status
            try
            {

                if (Request != null)
                {
                    HttpPostedFileBase file = model.File;
                    if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
                    {
                        string now = DateTime.Now.ConvertToTimestamp().ToString();
                        string fileExtension = System.IO.Path.GetExtension(file.FileName);
                        string fileName = string.Format("SALE_CDAO_{0}_{1}{2}", CurrentUserRecord.UserName, now, fileExtension);
                        if (fileExtension == ".xls" || fileExtension == ".xlsx")
                        {
                            var originalDirectory = new DirectoryInfo(Server.MapPath("~/File/OfferLetter/ChangeDaoRequest/"));
                            string fileLocation = UploadFile(originalDirectory, file, fileName);

                            DataTable dt = ConvertXSLXtoDataTable(fileLocation, fileExtension);
                            ChangeDaoRequestRecord changeDaoRequest = new ChangeDaoRequestRecord
                            {
                                ListChangeDaoCif = new List<ChangeDaoCifRecord>()
                            };
                            changeDaoRequest.Pic = CurrentUserRecord.UserName;
                            changeDaoRequest.Reason = model.Reason;
                            changeDaoRequest.ReasonDescription = model.ReasonDescription;
                            changeDaoRequest.BranchCodeSme = CurrentUserRecord.BranchCode;
                            changeDaoRequest.IsDeviation = model.IsDeviation;
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                var item = dt.Rows[i];
                                ChangeDaoCifRecord record = new ChangeDaoCifRecord
                                {
                                    Cif = item[1].ToString(),
                                    NewDao = item[2].ToString(),
                                };
                                changeDaoRequest.ListChangeDaoCif.Add(record);
                            }

                            DaoInfoViewModel vm = new DaoInfoViewModel();

                            if (changeDaoRequest.ListChangeDaoCif.Count == 0)
                            {
                                System.IO.File.Delete(fileLocation);
                                vm.MessageType = MessageType.Error;
                                vm.Message = "File không có dữ liệu";
                            }
                            else if (changeDaoRequest.ListChangeDaoCif.Any(x => string.IsNullOrEmpty(x.Cif) || string.IsNullOrEmpty(x.NewDao)))
                            {
                                vm.MessageType = MessageType.Error;
                                vm.Message = "File nhập vào có dữ liệu trống, kiểm tra lại file";
                            }
                            else
                            {
                                using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
                                {
                                    ResponseRecord response = null;
                                    UpdateChangeDaoRequestRequest request = new UpdateChangeDaoRequestRequest
                                    {
                                        Header = new RequestHeaderRecord
                                        {
                                            ApplicationKey = SystemConfiguration.ApplicationKey,
                                            CallerName = "SMEsCustomer360Degree.Controllers.AdminChecklistController.UpdateRule"
                                        },
                                        Record = changeDaoRequest,
                                        CurrentUser = CurrentUserRecord
                                    };
                                    response = serviceClient.Proxy.UpdateChangeDaoRequest(request);
                                    bool isUpdate = response.IsSuccess;

                                    if (!isUpdate)
                                    {
                                        System.IO.File.Delete(fileLocation);
                                        string cookieName = CurrentUserRecord.UserName + "CHDError";
                                        CreateCookie(cookieName, response.ErrorMessage);
                                    }
                                    else
                                    {
                                        string cookieName = CurrentUserRecord.UserName + "CHDSuccess";
                                        CreateCookie(cookieName, "Create request successfully");
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string cookieName = CurrentUserRecord.UserName + "CHDError";
                CreateCookie(cookieName, ex.Message);
                throw;
            }
            return RedirectToAction("ListChangeDaoRequest", "DaoManager");
        }

        [Authorize]
        [CustomActionFilter]
        [HttpPost]
        public ActionResult AddChangeDaoRequest(ChangeDaoViewModel vm)
        {
            try
            {
                ChangeDaoRequestRecord changeDaoRequest = new ChangeDaoRequestRecord
                {
                    ListChangeDaoCif = new List<ChangeDaoCifRecord>()
                };

                changeDaoRequest.Pic = CurrentUserRecord.UserName;
                changeDaoRequest.Reason = vm.Reason;
                changeDaoRequest.ReasonDescription = vm.ReasonDescription;
                changeDaoRequest.BranchCodeSme = CurrentUserRecord.BranchCode;
                changeDaoRequest.IsDeviation = vm.IsDeviation;

                var listCif = vm.Cif;
                listCif.ForEach(x =>
                {
                    changeDaoRequest.ListChangeDaoCif.Add(new ChangeDaoCifRecord
                    {
                        Cif = x,
                        NewDao = vm.NewDao,
                        OldDao = vm.OldDao
                    });
                });
                using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
                {
                    ResponseRecord response = null;
                    UpdateChangeDaoRequestRequest request = new UpdateChangeDaoRequestRequest
                    {
                        Header = new RequestHeaderRecord
                        {
                            ApplicationKey = SystemConfiguration.ApplicationKey,
                            CallerName = "SMEsCustomer360Degree.Controllers.AdminChecklistController.UpdateRule"
                        },
                        Record = changeDaoRequest,
                        CurrentUser = CurrentUserRecord
                    };
                    response = serviceClient.Proxy.UpdateChangeDaoRequest(request);
                    bool isUpdate = response.IsSuccess;

                    if (!isUpdate)
                    {
                        string cookieName = CurrentUserRecord.UserName + "CHDError";
                        CreateCookie(cookieName, response.ErrorMessage);
                    }
                    else
                    {
                        string cookieName = CurrentUserRecord.UserName + "CHDSuccess";
                        CreateCookie(cookieName, "Create request successfully");
                    }
                }
            }
            catch (Exception ex)
            {
                string cookieName = CurrentUserRecord.UserName + "CHDError";
                CreateCookie(cookieName, ex.Message);
            }
            return RedirectToAction("ListChangeDaoRequest", "DaoManager");
        }

        [Authorize]
        [CustomActionFilter]
        [HttpPost]
        public ActionResult ApproveChangeDaoRequest(int request)
        {
            ModelState.Clear(); //clear old status
            ChangeDaoRequestRecord userRequest = new ChangeDaoRequestRecord
            {
                Id = request,
                Status = (int)StatusChangeDaoEnum.Approve
            };
            var result = UpdateChangeDaoStatus(userRequest);
            return Json(result);
        }

        [Authorize]
        [HttpPost]
        public ActionResult ExportDataChangeDaoRequestToIT()
        {
            FilterRecord filter = new FilterRecord
            {
                CreateDaoRequestStatus = (int)StatusChangeDaoEnum.HOApproved
            };
            var customerRecords = RetrieveListChangeDaoRequest(filter);
            var resultCustomer = (customerRecords == null || customerRecords.Records == null) ? new List<ChangeDaoRequestRecord>() : customerRecords.Records;
            List<ExportChangeDaoRequestViewModel> listChangeDaoCif = new List<ExportChangeDaoRequestViewModel>();
            List<ExportChangeDaoAccountViewModel> listChangeDaoLD = new List<ExportChangeDaoAccountViewModel>();
            List<ExportChangeDaoAccountViewModel> listChangeDaoSTK = new List<ExportChangeDaoAccountViewModel>();
            List<ExportChangeDaoAccountViewModel> listChangeDaoAL = new List<ExportChangeDaoAccountViewModel>();
            List<ExportChangeDaoAccountViewModel> listChangeDaoMD = new List<ExportChangeDaoAccountViewModel>();
            string now = DateTime.Now.ToString("dd/MM/yyyy");
            resultCustomer.ForEach(x =>
            {
                List<ExportChangeDaoRequestViewModel> item = x.ListChangeDaoCif.Where(y => y.IsApproved).Select(y => new ExportChangeDaoRequestViewModel
                {
                    ChangeDaoRequestID = x.Id.ToString(),
                    Cif = y.Cif,
                    OldDao = y.OldDao,
                    NewDao = y.NewDao,
                    BranchCode = x.BranchId,
                    BusinessDate = now,
                    Segment = "SMEs"
                }).ToList();
                listChangeDaoCif.AddRange(item);

                x.ListChangeDaoCif.ForEach(y =>
                {
                    listChangeDaoLD.AddRange(y.ListChangeDaoProduct.Where(z => z.TypeProduct.Equals("LD")).Select(z => new ExportChangeDaoAccountViewModel
                    {
                        ChangeDaoRequestId = x.Id.ToString(),
                        NoProduct = z.NoProduct,
                        OldDao = z.Dao,
                        NewDao = y.NewDao,
                        BranchCode = x.BranchId,
                        BusinessDate = now,
                        Cif = y.Cif,
                        Segment = "SMEs"
                    }).ToList());
                    listChangeDaoSTK.AddRange(y.ListChangeDaoProduct.Where(z => z.TypeProduct.Equals("STK")).Select(z => new ExportChangeDaoAccountViewModel
                    {
                        ChangeDaoRequestId = x.Id.ToString(),
                        NoProduct = z.NoProduct,
                        OldDao = z.Dao,
                        NewDao = y.NewDao,
                        BranchCode = x.BranchId,
                        BusinessDate = now,
                        Cif = y.Cif,
                        Segment = "SMEs"
                    }).ToList());
                    listChangeDaoAL.AddRange(y.ListChangeDaoProduct.Where(z => z.TypeProduct.Equals("AL")).Select(z => new ExportChangeDaoAccountViewModel
                    {
                        ChangeDaoRequestId = x.Id.ToString(),
                        NoProduct = z.NoProduct,
                        OldDao = z.Dao,
                        NewDao = y.NewDao,
                        BranchCode = x.BranchId,
                        BusinessDate = now,
                        Cif = y.Cif,
                        Segment = "SMEs"
                    }).ToList());
                    listChangeDaoMD.AddRange(y.ListChangeDaoProduct.Where(z => z.TypeProduct.Equals("MD")).Select(z => new ExportChangeDaoAccountViewModel
                    {
                        ChangeDaoRequestId = x.Id.ToString(),
                        NoProduct = z.NoProduct,
                        OldDao = z.Dao,
                        NewDao = y.NewDao,
                        BranchCode = x.BranchId,
                        BusinessDate = now,
                        Cif = y.Cif,
                        Segment = "SMEs"
                    }).ToList());
                });

            });
            List<DataTable> listDT = new List<DataTable>();

            DataTable dtRequest = new DataTable();
            dtRequest = ToDataTable(resultCustomer.GroupBy(x => x.Id).Select(x => new { RequestId = x.Key }).ToList());
            dtRequest.TableName = "Change Dao Request ID";
            listDT.Add(dtRequest);

            DataTable dt = new DataTable();
            dt = ToDataTable(listChangeDaoCif);
            dt.TableName = "Dao CIF";
            listDT.Add(dt);

            DataTable dt1 = new DataTable();
            dt1 = ToDataTable(listChangeDaoLD);
            dt1.TableName = "Dao LD";
            listDT.Add(dt1);

            DataTable dt2 = new DataTable();
            dt2 = ToDataTable(listChangeDaoSTK);
            dt2.TableName = "Dao STK";
            listDT.Add(dt2);

            DataTable dt3 = new DataTable();
            dt3 = ToDataTable(listChangeDaoAL);
            dt3.TableName = "Dao AL";
            listDT.Add(dt3);

            DataTable dt4 = new DataTable();
            dt4 = ToDataTable(listChangeDaoMD);
            dt4.TableName = "Dao MD";
            listDT.Add(dt4);
            var fileName = "Request Change Dao SME " + DateTime.Now.ToShortDateString() + ".xlsx";

            fileName = fileName.Replace("/", "");
            ExportMultiSheetToExcel(listDT, fileName);
            bool isSucces = UpdateStatusListChangeDaoRequest(customerRecords.Records, (int)StatusChangeDaoEnum.ITProcessing);
            return RedirectToAction("ListChangeDaoRequest", "DaoManager");
        }


        [Authorize]
        [HttpPost]
        public ActionResult ExportDataChangeDaoRequestDeviation(ChangeDaoViewModel vm)
        {
            DateTime currentDate = DateTime.Now;
            var fromDate = DateTime.MinValue.ToString("dd/MM/yyyy");
            var toDate = DateTime.Now.ToString("dd/MM/yyyy");

            FilterRecord filter = new FilterRecord
            {
                IsExport = true,
                IsExportDeviation = vm.IsDeviation,
                RequestStatus = vm.Status.ToString(),
                Description = vm.Reason.ToString(),
            };
            if (!string.IsNullOrEmpty(vm.CreateDateRange))
            {
                filter.CusOpenDate = vm.CreateDateRange;
            }
            else
            {
                filter.CusOpenDate = string.Format("{0}-{1}", fromDate, toDate);
            }
            var customerRecords = new RetrieveListChangeDaoRequestResponse();
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {
                RetrieveListChangeDaoRequestRequest request = new RetrieveListChangeDaoRequestRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.DaoManagerController.RetrieveListCreateDaoRequest"
                    },
                    Page = new PageRecord
                    {
                        PageSize = 0,
                        PageIndex = 0
                    },
                    Sort = new SortRecord
                    {
                    },
                    CurrentUser = CurrentUserRecord,
                    Filter = filter
                };
                customerRecords = serviceClient.Proxy.RetrieveListChangeDaoForExportRequest(request);
            }
            var resultCustomer = (customerRecords == null || customerRecords.Records == null) ? new List<ChangeDaoRequestRecord>() : customerRecords.Records;
            List<ExportChangeDaoRequestViewModel> listChangeDaoCif = new List<ExportChangeDaoRequestViewModel>();
            List<ExportChangeDaoAccountViewModel> listChangeDaoLD = new List<ExportChangeDaoAccountViewModel>();
            List<ExportChangeDaoAccountViewModel> listChangeDaoSTK = new List<ExportChangeDaoAccountViewModel>();
            List<ExportChangeDaoAccountViewModel> listChangeDaoAL = new List<ExportChangeDaoAccountViewModel>();
            List<ExportChangeDaoAccountViewModel> listChangeDaoMD = new List<ExportChangeDaoAccountViewModel>();
            string now = currentDate.ToString("dd/MM/yyyy");
            resultCustomer.ForEach(x =>
            {
                List<ExportChangeDaoRequestViewModel> item = x.ListChangeDaoCif.Where(y => y.IsApproved).Select(y => new ExportChangeDaoRequestViewModel
                {
                    ChangeDaoRequestID = x.Id.ToString(),
                    Cif = y.Cif,
                    OldDao = y.OldDao,
                    NewDao = y.NewDao,
                    BranchCode = x.BranchId,
                    BusinessDate = x.CreatedDate.ToString("dd/MM/yyyy"),
                    Segment = "SMEs"
                }).ToList();
                listChangeDaoCif.AddRange(item);

                x.ListChangeDaoCif.ForEach(y =>
                {
                    listChangeDaoLD.AddRange(y.ListChangeDaoProduct.Where(z => z.TypeProduct.Equals("LD")).Select(z => new ExportChangeDaoAccountViewModel
                    {
                        ChangeDaoRequestId = x.Id.ToString(),
                        NoProduct = z.NoProduct,
                        OldDao = z.Dao,
                        NewDao = y.NewDao,
                        BranchCode = x.BranchId,
                        BusinessDate = x.CreatedDate.ToString(),
                        Cif = y.Cif,
                        Segment = "SMEs"
                    }).ToList());
                    listChangeDaoSTK.AddRange(y.ListChangeDaoProduct.Where(z => z.TypeProduct.Equals("STK")).Select(z => new ExportChangeDaoAccountViewModel
                    {
                        ChangeDaoRequestId = x.Id.ToString(),
                        NoProduct = z.NoProduct,
                        OldDao = z.Dao,
                        NewDao = y.NewDao,
                        BranchCode = x.BranchId,
                        BusinessDate = x.CreatedDate.ToString(),
                        Cif = y.Cif,
                        Segment = "SMEs"
                    }).ToList());
                    listChangeDaoAL.AddRange(y.ListChangeDaoProduct.Where(z => z.TypeProduct.Equals("AL")).Select(z => new ExportChangeDaoAccountViewModel
                    {
                        ChangeDaoRequestId = x.Id.ToString(),
                        NoProduct = z.NoProduct,
                        OldDao = z.Dao,
                        NewDao = y.NewDao,
                        BranchCode = x.BranchId,
                        BusinessDate = x.CreatedDate.ToString(),
                        Cif = y.Cif,
                        Segment = "SMEs"
                    }).ToList());
                    listChangeDaoMD.AddRange(y.ListChangeDaoProduct.Where(z => z.TypeProduct.Equals("MD")).Select(z => new ExportChangeDaoAccountViewModel
                    {
                        ChangeDaoRequestId = x.Id.ToString(),
                        NoProduct = z.NoProduct,
                        OldDao = z.Dao,
                        NewDao = y.NewDao,
                        BranchCode = x.BranchId,
                        BusinessDate = x.CreatedDate.ToString(),
                        Cif = y.Cif,
                        Segment = "SMEs"
                    }).ToList());
                });

            });
            List<DataTable> listDT = new List<DataTable>();

            DataTable dtRequest = new DataTable();
            dtRequest = ToDataTable(resultCustomer.Select(x => new
            {
                Branch = x.Branch,
                RequestId = x.Id,
                PIC = x.Pic,
                Status = x.RejectPerson + EnumHelper<StatusChangeDaoEnum>.GetDisplayValue((StatusChangeDaoEnum)x.Status),
                Reason = EnumHelper<ReasonChangeDaoEnum>.GetDisplayValue((ReasonChangeDaoEnum)x.Reason) + x.ReasonDescription,
                CreateDate = x.CreatedDate.ToString()
            }).ToList());
            dtRequest.TableName = "Change Dao Request ID";
            listDT.Add(dtRequest);

            DataTable dt = new DataTable();
            dt = ToDataTable(listChangeDaoCif);
            dt.TableName = "Dao CIF";
            listDT.Add(dt);

            DataTable dt1 = new DataTable();
            dt1 = ToDataTable(listChangeDaoLD);
            dt1.TableName = "Dao LD";
            listDT.Add(dt1);

            DataTable dt2 = new DataTable();
            dt2 = ToDataTable(listChangeDaoSTK);
            dt2.TableName = "Dao STK";
            listDT.Add(dt2);

            DataTable dt3 = new DataTable();
            dt3 = ToDataTable(listChangeDaoAL);
            dt3.TableName = "Dao AL";
            listDT.Add(dt3);

            DataTable dt4 = new DataTable();
            dt4 = ToDataTable(listChangeDaoMD);
            dt4.TableName = "Dao MD";
            listDT.Add(dt4);
            var fileName = "Request Change Dao Deviation SME " + currentDate.ToShortDateString() + ".xlsx";

            fileName = fileName.Replace("/", "");
            ExportMultiSheetToExcel(listDT, fileName);
            return RedirectToAction("ListChangeDaoRequest", "DaoManager");
        }
        #endregion

        #region Create Dao Ajax Methods
        [Authorize]
        [HttpPost]
        public ActionResult ImportFormCreateDaoRequest(FormCollection formCollection)
        {
            bool isUpdate = false;
            string errorMessage = string.Empty;
            DaoInfoViewModel vm = new DaoInfoViewModel();
            try
            {
                if (Request != null)
                {
                    HttpPostedFileBase file = Request.Files["UploadedFile"];

                    if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
                    {
                        string now = DateTime.Now.ConvertToTimestamp().ToString();
                        string fileExtension = System.IO.Path.GetExtension(file.FileName);
                        string fileName = string.Format("SSO_RDAO_{0}_{1}{2}", CurrentUserRecord.UserName, now, fileExtension);
                        if (fileExtension == ".xls" || fileExtension == ".xlsx")
                        {
                            var originalDirectory = new DirectoryInfo(Server.MapPath("~/File/OfferLetter/"));
                            string fileLocation = UploadFile(originalDirectory, file, fileName);

                            DataTable dt = ConvertXSLXtoDataTable(fileLocation, fileExtension);
                            List<RequestCreateDaoRecord> listRequest = new List<RequestCreateDaoRecord>();
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                var item = dt.Rows[i];
                                if (!string.IsNullOrEmpty(item[1].ToString()))
                                {
                                    RequestCreateDaoRecord record = new RequestCreateDaoRecord
                                    {
                                        FullName = item[1].ToString(),
                                        PositionName = item[3].ToString(),
                                        StaffId = item[4].ToString(),
                                        Email = item[5].ToString(),
                                        Cif = item[6].ToString(),
                                        LegalId = item[7].ToString(),
                                        Phone = item[8].ToString(),
                                        PathOfferLetter = string.Empty,
                                        BranchId = CurrentUserRecord.BranchCode
                                    };
                                    listRequest.Add(record);
                                }
                            }

                            if (listRequest.Count == 0)
                            {
                                System.IO.File.Delete(fileLocation);
                                isUpdate = false;
                                errorMessage = "File không có dữ liệu";
                            }
                            else if (listRequest.Any(x => string.IsNullOrEmpty(x.FullName) || string.IsNullOrEmpty(x.PositionName) || string.IsNullOrEmpty(x.StaffId) || string.IsNullOrEmpty(x.Email) || string.IsNullOrEmpty(x.Cif) || string.IsNullOrEmpty(x.LegalId) || string.IsNullOrEmpty(x.Phone)))
                            {
                                isUpdate = false;
                                errorMessage = "File nhập vào có dữ liệu trống, kiểm tra lại file";
                            }
                            else
                            {
                                using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
                                {
                                    ResponseRecord response = null;
                                    UpdateCreateDaoRequestRequest request = new UpdateCreateDaoRequestRequest
                                    {
                                        Header = new RequestHeaderRecord
                                        {
                                            ApplicationKey = SystemConfiguration.ApplicationKey,
                                            CallerName = "SMEsCustomer360Degree.Controllers.AdminChecklistController.UpdateRule"
                                        },
                                        ListCreateDaoRequest = listRequest,
                                        CurrentUser = CurrentUserRecord
                                    };
                                    response = serviceClient.Proxy.UpdateRequestDaoByList(request);
                                    isUpdate = response.IsSuccess;
                                    if (!response.IsSuccess)
                                    {
                                        errorMessage = response.ErrorMessage;
                                    }
                                }
                            }
                        }
                        else
                        {
                            isUpdate = false;
                            errorMessage = "File sai định dạng";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                isUpdate = false;
                errorMessage = ex.Message;
            }
            if (!isUpdate)
            {
                string cookieName = CurrentUserRecord.UserName + "CRDError";
                CreateCookie(cookieName, errorMessage);
                return RedirectToAction("AddCreateDaoRequest", "DaoManager", vm);
            }
            else
            {
                string cookieName = CurrentUserRecord.UserName + "CRDSuccess";
                CreateCookie(cookieName, "Create request successfully");
                return RedirectToAction("ListRequestCreateDao", "DaoManager", vm);
            }
        }

        [Authorize]
        [HttpPost]
        public ActionResult ApproveRequestCreateDao(int request)
        {
            ResponseRecord result = new ResponseRecord();
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {
                RequestCreateDaoRecord userRequest = new RequestCreateDaoRecord
                {
                    RequestId = request,
                    StatusCreateDaoRequest = (int)StatusRequestCreateDaoEnum.Approve
                };
                UpdateCreateDaoRequestRequest requestUpdate = new UpdateCreateDaoRequestRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.DaoManager.ApproveRequestCreateDao"
                    },
                    Record = userRequest,
                    CurrentUser = CurrentUserRecord
                };
                result = serviceClient.Proxy.UpdateStatusRequestDao(requestUpdate);
            }
            return Json(result);
        }

        [Authorize]
        [HttpPost]
        public ActionResult RejectCreateDaoRequest(int request)
        {
            ResponseRecord result = new ResponseRecord();
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {
                RequestCreateDaoRecord userRequest = new RequestCreateDaoRecord
                {
                    RequestId = request,
                    StatusCreateDaoRequest = (int)StatusRequestCreateDaoEnum.Reject,
                    RejectPerson = CurrentUserRecord.UserName
                };
                UpdateCreateDaoRequestRequest requestUpdate = new UpdateCreateDaoRequestRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.DaoManager.ApproveRequestCreateDao"
                    },
                    Record = userRequest,
                    CurrentUser = CurrentUserRecord
                };
                result = serviceClient.Proxy.UpdateStatusRequestDao(requestUpdate);
            }
            return Json(result);
        }

        [Authorize]
        [HttpPost]
        public ActionResult RejectReasonCreateDaoRequest(DaoInfoViewModel vm)
        {
            ResponseRecord result = new ResponseRecord();
            bool isUpdate = true;
            string errorMessage = string.Empty;
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {
                RequestCreateDaoRecord userRequest = new RequestCreateDaoRecord
                {
                    RequestId = vm.Id,
                    StatusCreateDaoRequest = (int)StatusRequestCreateDaoEnum.Reject,
                    RejectReason = vm.RejectReason
                };
                UpdateCreateDaoRequestRequest requestUpdate = new UpdateCreateDaoRequestRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.DaoManager.ApproveRequestCreateDao"
                    },
                    Record = userRequest,
                    CurrentUser = CurrentUserRecord
                };
                result = serviceClient.Proxy.UpdateRejectReason(requestUpdate);
                isUpdate = result.IsSuccess;
                if (!result.IsSuccess)
                {
                    errorMessage = result.ErrorMessage;
                }
            }
            if (!isUpdate)
            {
                string cookieName = CurrentUserRecord.UserName + "CRDError";
                CreateCookie(cookieName, errorMessage);
            }
            else
            {
                string cookieName = CurrentUserRecord.UserName + "CRDSuccess";
                CreateCookie(cookieName, "Reject Request successfull");
            }
            return RedirectToAction("ListRequestCreateDao", "DaoManager", vm);
        }

        [Authorize]
        [HttpPost]
        public ActionResult CreateDaoRequestInfo(string id)
        {
            int RequestId = int.Parse(id);
            RequestCreateDaoRecord resultCustomer = new RequestCreateDaoRecord();
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {
                RetrieveCreateDaoRequestByIdRequest request = new RetrieveCreateDaoRequestByIdRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.CustomerManagerController.CustomerInfo"
                    },
                    CurrentUser = CurrentUserRecord,
                    RequestId = RequestId
                };
                var customerRecords = new RetrieveCreateDaoRequestByIdResponse();
                customerRecords = serviceClient.Proxy.RetrieveCreateDaoRequestById(request);
                resultCustomer = (customerRecords == null || customerRecords.Record == null) ? new RequestCreateDaoRecord() : customerRecords.Record;
            }
            var objectItem = new
            {
                fullName = resultCustomer.FullName,
                position = resultCustomer.PositionName,
                staffId = resultCustomer.StaffId,
                email = resultCustomer.Email,
                cif = resultCustomer.Cif,
                legalId = resultCustomer.LegalId,
                phone = resultCustomer.Phone,
                branch = resultCustomer.Branch,
                DAO = resultCustomer.Dao
            };
            return Json(objectItem);
        }

        [Authorize]
        [HttpPost]
        public ActionResult ExportDataRequestToIT()
        {
            FilterRecord filter = new FilterRecord
            {
                IsExport = true
            };
            var customerRecords = RetrieveListCreateDaoRequest(filter);
            var resultCustomer = (customerRecords == null || customerRecords.Records == null) ? new List<ExportCreateDaoRequestViewModel>() : customerRecords.Records.Select(x => new ExportCreateDaoRequestViewModel
            {
                Dao = string.Empty,
                Area = x.Branch,
                Name = x.FullName.NonUnicode(),
                Delivery = x.PositionName,
                Level = "60",
                DeparmentParent = x.BranchId.Substring(x.BranchId.Length - 3),
                StaffId = x.StaffId,
                Cif = x.Cif,
                FromDate = DateTime.Now.ToShortDateString(),
                ToDate = string.Empty,
                Id = x.RequestId.ToString()
            }).ToList();
            DataTable dt = new DataTable();
            dt.TableName = "Total Request ";
            var fileName = "Request Create DAO SME " + DateTime.Now.ToShortDateString() + ".xlsx";

            fileName = fileName.Replace("/", "");
            dt = ToDataTable(resultCustomer);
            ExportToExcel(dt, fileName);
            bool isSucces = UpdateStatusListCreateDaoRequest(customerRecords.Records, (int)StatusRequestCreateDaoEnum.ITProcessing);
            return RedirectToAction("ListRequestCreateDao", "DaoManager");
        }

        [Authorize]
        [HttpPost]
        public ActionResult ImportResultCreateDaoRequest(FormCollection formCollection)
        {
            bool isUpdate = false;
            string errorMessage = string.Empty;
            if (Request != null)
            {
                try
                {

                    HttpPostedFileBase file = Request.Files["UploadedFile"];

                    if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
                    {
                        string now = DateTime.Now.ConvertToTimestamp().ToString();
                        string fileExtension = System.IO.Path.GetExtension(file.FileName);
                        string fileName = string.Format("BIC_RDAO_{0}_{1}{2}", CurrentUserRecord.UserName, now, fileExtension);
                        if (fileExtension == ".xls" || fileExtension == ".xlsx")
                        {
                            var originalDirectory = new DirectoryInfo(Server.MapPath("~/File/OfferLetter/"));
                            string fileLocation = UploadFile(originalDirectory, file, fileName);

                            DataTable dt = ConvertXSLXtoDataTable(fileLocation, fileExtension);
                            List<RequestCreateDaoRecord> listRequest = new List<RequestCreateDaoRecord>();
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                var item = dt.Rows[i];
                                RequestCreateDaoRecord record = new RequestCreateDaoRecord
                                {
                                    Dao = item[0].ToString(),
                                    FullName = item[2].ToString(),
                                    PositionName = item[3].ToString(),
                                    StaffId = item[6].ToString(),
                                    Cif = item[7].ToString()
                                };
                                listRequest.Add(record);
                            }

                            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
                            {
                                ResponseRecord response = null;

                                UpdateCreateDaoRequestRequest request = new UpdateCreateDaoRequestRequest
                                {
                                    Header = new RequestHeaderRecord
                                    {
                                        ApplicationKey = SystemConfiguration.ApplicationKey,
                                        CallerName = "SMEsCustomer360Degree.Controllers.AdminChecklistController.UpdateRule"
                                    },
                                    ListCreateDaoRequest = listRequest,
                                    CurrentUser = CurrentUserRecord
                                };
                                response = serviceClient.Proxy.UpdateResultCreateDaoByList(request);
                                isUpdate = response.IsSuccess;
                                string error = response.ErrorMessage;
                                if (!response.IsSuccess)
                                {
                                    System.IO.File.Delete(fileLocation);
                                    errorMessage = response.ErrorMessage;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    isUpdate = false;
                    errorMessage = ex.ToString();
                }
            }
            if (!isUpdate)
            {
                string cookieName = CurrentUserRecord.UserName + "CRDError";
                CreateCookie(cookieName, errorMessage);
            }
            else
            {
                string cookieName = CurrentUserRecord.UserName + "CRDSuccess";
                CreateCookie(cookieName, "Upload successfull");
            }
            return RedirectToAction("ListRequestCreateDao", "DaoManager");
        }
        [Authorize]
        [HttpPost]
        public ActionResult UploadOfferLetter(DaoInfoViewModel vm)
        {
            DaoInfoViewModel model = new DaoInfoViewModel();
            bool isUpdate = false;
            string errorMessage = string.Empty;
            model.CurrentUser = CurrentUserRecord;
            try
            {
                HttpPostedFileBase file = vm.File;
                if (file != null && file.ContentLength > 0)
                {
                    var fName = file.FileName;
                    if (ALLOW_FILE_DAO_MANAGEMENT.Contains(Path.GetExtension(fName).ToLower()))
                    {
                        var originalDirectory = new DirectoryInfo(string.Format("{0}File/OfferLetter/{1}/{2}", Server.MapPath(@"\"), DateTime.Now.Year, DateTime.Now.Month));
                        string linkFileLocation = UploadFile(originalDirectory, file);

                        var linkFile = string.Format("/File/OfferLetter/{0}/{1}/{2}", DateTime.Now.Year, DateTime.Now.Month, file.FileName);
                        using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
                        {
                            ResponseRecord response = null;

                            RequestCreateDaoRecord userRequest = new RequestCreateDaoRecord
                            {
                                RequestId = vm.Id,
                                PathOfferLetter = linkFile
                            };
                            UpdateCreateDaoRequestRequest request = new UpdateCreateDaoRequestRequest
                            {
                                Header = new RequestHeaderRecord
                                {
                                    ApplicationKey = SystemConfiguration.ApplicationKey,
                                    CallerName = "SMEsCustomer360Degree.Controllers.AdminChecklistController.UpdateRule"
                                },
                                CurrentUser = CurrentUserRecord,
                                Record = userRequest
                            };
                            response = serviceClient.Proxy.UploadOfferLetter(request);
                            isUpdate = response.IsSuccess;
                            if (!response.IsSuccess)
                            {
                                errorMessage = response.ErrorMessage;
                            }
                        }

                    }
                    else
                    {
                        isUpdate = false;
                        errorMessage = "File sai định dạng";
                    }
                }
            }
            catch (Exception ex)
            {
                isUpdate = false;
                errorMessage = ex.ToString();
            }
            if (!isUpdate)
            {
                string cookieName = CurrentUserRecord.UserName + "CRDError";
                CreateCookie(cookieName, errorMessage);
            }
            else
            {
                string cookieName = CurrentUserRecord.UserName + "CRDSuccess";
                CreateCookie(cookieName, "Upload successfull");
            }
            return RedirectToAction("ListRequestCreateDao", "DaoManager", model);
        }

        #endregion

        #region Private Methods
        private RetrieveListRequestCreateDaoByUserResponse RetrieveListCreateDaoRequest(FilterRecord filter, DataTablesPageRequest pageRequest = null)
        {
            RetrieveListRequestCreateDaoByUserResponse result = new RetrieveListRequestCreateDaoByUserResponse();

            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {

                RetrieveListRequestCreateDaoByUserRequest request = new RetrieveListRequestCreateDaoByUserRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.DaoManagerController.RetrieveListCreateDaoRequest"
                    },
                    Page = new PageRecord
                    {
                        PageSize = pageRequest == null ? 0 : pageRequest.DisplayLength,
                        PageIndex = pageRequest == null ? 0 : pageRequest.DisplayLength > 0 ? pageRequest.DisplayStart / pageRequest.DisplayLength : 0
                    },
                    Sort = new SortRecord
                    {
                        SortDir = pageRequest == null ? new List<string>() : pageRequest.SortDir
                    },
                    CurrentUser = CurrentUserRecord,
                    Filter = filter
                };
                result = serviceClient.Proxy.RetrieveListRequestCreateDaoByUser(request);
            }
            return result;
        }
        private RetrieveListChangeDaoRequestResponse RetrieveListChangeDaoRequest(FilterRecord filter, DataTablesPageRequest pageRequest = null)
        {
            RetrieveListChangeDaoRequestResponse result = new RetrieveListChangeDaoRequestResponse();

            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {

                RetrieveListChangeDaoRequestRequest request = new RetrieveListChangeDaoRequestRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.DaoManagerController.RetrieveListCreateDaoRequest"
                    },
                    Page = new PageRecord
                    {
                        PageSize = pageRequest == null ? 0 : pageRequest.DisplayLength,
                        PageIndex = pageRequest == null ? 0 : pageRequest.DisplayLength > 0 ? pageRequest.DisplayStart / pageRequest.DisplayLength : 0
                    },
                    CurrentUser = CurrentUserRecord,
                    Filter = filter
                };
                result = serviceClient.Proxy.RetrieveListChangeDaoForExportRequest(request);
            }
            return result;
        }
        private bool UpdateStatusListCreateDaoRequest(List<RequestCreateDaoRecord> listRequest, int status)
        {
            ResponseRecord result = new ResponseRecord();
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {
                listRequest.ForEach(x =>
                {
                    x.StatusCreateDaoRequest = status;
                });
                UpdateCreateDaoRequestRequest requestUpdate = new UpdateCreateDaoRequestRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.DaoManager.ApproveRequestCreateDao"
                    },
                    CurrentUser = CurrentUserRecord,
                    ListCreateDaoRequest = listRequest
                };
                result = serviceClient.Proxy.UpdateStatusListRequestDao(requestUpdate);
            }
            return result.IsSuccess;
        }
        private bool UpdateStatusListChangeDaoRequest(List<ChangeDaoRequestRecord> listRequest, int status)
        {
            ResponseRecord result = new ResponseRecord();
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {
                listRequest.ForEach(x =>
                {
                    x.Status = status;
                });
                UpdateChangeDaoRequestRequest requestUpdate = new UpdateChangeDaoRequestRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.DaoManager.ApproveRequestCreateDao"
                    },
                    CurrentUser = CurrentUserRecord,
                    ListChangeDaoRequest = listRequest
                };
                result = serviceClient.Proxy.UpdateStatusListChangeDaoRequest(requestUpdate);
            }
            return result.IsSuccess;
        }
        private ResponseRecord UpdateChangeDaoStatus(ChangeDaoRequestRecord userRequest)
        {
            ResponseRecord result = new ResponseRecord();
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {
                UpdateChangeDaoRequestRequest requestUpdate = new UpdateChangeDaoRequestRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.DaoManager.ApproveRequestCreateDao"
                    },
                    Record = userRequest,
                    CurrentUser = CurrentUserRecord
                };
                result = serviceClient.Proxy.UpdateChangeDaoStatus(requestUpdate);
            }
            return result;
        }

        #endregion
    }
}